package com.yhao.stocknew.common.service;

import com.alibaba.fastjson.JSONArray;
import com.gargoylesoftware.htmlunit.*;
import com.yhao.stocknew.common.listener.MyJSErrorListener;
import com.yhao.stocknew.common.utils.JsonUtil;
import com.yhao.stocknew.entity.HisInfo;
import com.yhao.stocknew.service.HisInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author : yhao
 * @Date : 2023/11/10 - 11:38
 * @Desc : 搜狐API接口处理类
 */
@Slf4j
@Service
public class SHService {

    WebClient webClient = null;
    Map<String, String> additionalHeaders = null;


    //初始化
    public SHService() {
        webClient = new WebClient(BrowserVersion.CHROME);//新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
        webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);//是否启用CSS, 因为不需要展现页面, 所以不需要启用
        webClient.getOptions().setJavaScriptEnabled(true); //很重要，启用JS。有些网站要开启！
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());//很重要，设置支持AJAX
        webClient.getOptions().setTimeout(30000);
        // javascript 异常处理
        webClient.setJavaScriptErrorListener(new MyJSErrorListener());
        webClient.setJavaScriptTimeout(10000);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);

        additionalHeaders = new HashMap<>();
        additionalHeaders
                .put("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36");
        additionalHeaders.put("Accept-Language", "zh-CN,zh;q=0.8");
        additionalHeaders.put("Accept", "*/*");

    }

    @Autowired
    private HisInfoService hisInfoService;

    /**
     * @param code
     * @param name
     * @param startDate
     * @param endDate
     * @return
     * @desc 获取历史数据
     */
    public boolean getHisInfo(String code, String name, String startDate, String endDate) {
        boolean saveBatch = false;
        String url = "https://q.stock.sohu.com/hisHq?code=cn_" + code + "&start=" + startDate + "&end=" + endDate;
        log.info("执行到这里了哈--------->" + url);
        HisInfo hisInfo = null;
        List<HisInfo> finalList = new ArrayList();

        String content = "";
        try {
            WebRequest request = new WebRequest(new URL(url), HttpMethod.GET);
            request.setAdditionalHeaders(additionalHeaders);
            Page page = webClient.getPage(request);
            String response = page.getWebResponse().getContentAsString();
            if (response != null && response.length() > 0) {
                List<Map<String, Object>> listObjectFir = (List<Map<String, Object>>) JSONArray.parse(response);
                final Map<String, Object> stringStringMap = listObjectFir.get(0);
                final JSONArray contents = (JSONArray) stringStringMap.get("hq");
                final Object[] objects = contents.toArray();

                String turnoverRate = "";
                for (Object object : objects) {
                    content = object.toString();
                    if (content == null || "".equals(content)) {
                        log.info("获取数据为空:============>>>" + code);
                        continue;
                    }
                    final List<Object> resultList = JsonUtil.jsonToList(content);
                    if (resultList.get(9).toString().contains("-")) {
                        turnoverRate = "0";
                    } else {
                        turnoverRate = resultList.get(9).toString().replace("%", "");
                    }

                    hisInfo = new HisInfo(code,
                            name,
                            new BigDecimal(resultList.get(2).toString()),
                            new BigDecimal(resultList.get(4).toString().replace("%", "")),
                            new BigDecimal(resultList.get(3).toString()),
                            new BigDecimal(turnoverRate),
                            new BigDecimal(resultList.get(8).toString()),
                            resultList.get(0).toString(),
                            LocalDateTime.now());
                    finalList.add(hisInfo);

                }

                log.info("数据总长度===>>>" + finalList.size());
                int batchSize = 200;
                for (int i = 0; i < finalList.size(); i += batchSize) {
                    List<HisInfo> subList = finalList.subList(i, Math.min(i + batchSize, finalList.size()));
                    saveBatch = hisInfoService.saveBatch(subList);
                }

                // 随机休眠
                Thread.sleep(new Random().nextInt(1000) + 3000);

                log.info("saveBatch执行完成了");
            }
        } catch (Exception e) {
            log.error("content==========>>>" + content);
            // e.printStackTrace();

            log.error("url解析错误：" + url);
        }
        return saveBatch;
    }


}
